<template>
  <div class="app-container">
    <!-- 左侧知识库列表 -->
    <div class="sidebar">
      <div class="sidebar-header">
        <div style="display: flex; align-items: center; gap: 10px">
          <button
            class="back-btn"
            @click="goBack"
            style="background: none; border: none; color: #666; cursor: pointer"
          >
            <i class="fas fa-arrow-left"></i>
          </button>
          <span>知识库</span>
        </div>
        <button class="add-kb-btn" @click="openKnowledgeBaseModal">
          <i class="fas fa-plus"></i>
        </button>
      </div>
      <div class="kb-list" id="kb-list">
        <!-- 知识库列表 -->
        <div
          class="empty-state"
          v-if="!knowledgeBases || knowledgeBases.length === 0"
          id="empty-kb-state"
        >
          <i class="fas fa-database"></i>
          <p>暂无知识库</p>
          <p>点击右上角"+"按钮创建知识库</p>
        </div>
        <div v-else>
          <div
            v-for="kb in knowledgeBases"
            :key="kb.id"
            class="kb-item"
            :class="{ active: currentKbId === kb.id }"
            @click="selectKnowledgeBase(kb)"
            :data-id="kb.id"
          >
            <div class="kb-content">
              <div class="kb-name">{{ kb.name }}</div>
              <div class="kb-info">
                {{ kb.is_default ? '默认知识库' : '自定义知识库' }} ·
                {{ kb.embedding_model }}
              </div>
            </div>
            <div class="kb-actions">
              <button
                class="kb-action-btn"
                @click.stop="handleDeleteKb(kb)"
                title="删除知识库"
                :disabled="kb.is_default"
              >
                <i class="fas fa-trash-alt"></i>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧文件列表 -->
    <div class="main-content">
      <div class="content-header">
        <div class="current-kb-name" id="current-kb-name">
          <i class="fas fa-database"></i>
          <span id="kb-name-display">{{
            currentKbName || '请选择知识库'
          }}</span>
        </div>
        <button
          class="upload-btn"
          id="upload-btn"
          @click="triggerFileUpload"
          v-if="currentKbId"
        >
          <i class="fas fa-upload"></i> 添加文件
        </button>
        <input
          ref="fileInput"
          type="file"
          id="file-input"
          style="display: none"
          multiple
          @change="handleFileUpload"
        />
      </div>

      <div class="file-tabs">
        <div class="file-tab active">
          文件 (<span id="file-count">{{ files.length || 0 }}</span
          >)
        </div>
      </div>

      <div class="file-content">
        <div
          class="upload-area"
          id="upload-area"
          @dragover.prevent="handleDragOver"
          @dragleave.prevent="handleDragLeave"
          @drop.prevent="handleDrop"
          :style="uploadAreaStyle"
        >
          <template v-if="uploading">
            <i
              class="fas fa-spinner fa-spin"
              style="font-size: 3em; color: #3498db; margin-bottom: 10px"
            ></i>
            <p>上传中，请稍候...</p>
          </template>
          <template v-else>
            <i
              class="fas fa-cloud-upload-alt"
              style="font-size: 3em; color: #999; margin-bottom: 10px"
            ></i>
            <p>拖拽文件到这里或点击"添加文件"按钮</p>
            <p style="font-size: 0.85em; color: #666">
              支持TXT, MD, HTML, PDF, DOCX, PPTX, XLSX, EPUB...格式
            </p>
          </template>
        </div>

        <div class="file-list" id="file-list">
          <div
            v-if="(!files || files.length === 0) && currentKbId"
            class="empty-state"
            id="empty-file-state"
          >
            <i class="fas fa-file"></i>
            <p>暂无文件</p>
            <p>点击"添加文件"按钮上传文件</p>
          </div>
          <!-- 文件列表 -->
          <div v-else-if="files">
            <div v-for="file in files" :key="file.id" class="file-item">
              <div class="file-info">
                <div class="file-icon">
                  <i class="far fa-file"></i>
                </div>
                <div class="file-details">
                  <div class="file-name">{{ file.original_name }}</div>
                  <div class="file-meta">
                    {{ formatDate(file.uploaded_at) }}
                  </div>
                </div>
              </div>
              <div class="file-actions">
                <span class="file-status">
                  <i class="fas fa-check"></i> 已完成
                </span>
                <button
                  class="file-action-btn"
                  @click="handleDeleteFile(file)"
                  title="删除文件"
                >
                  <i class="fas fa-trash-alt"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'KnowledgeBases',
  data() {
    return {
      currentKbId: null,
      currentKbName: '',
      knowledgeBases: [],
      files: [],
      uploading: false,
      uploadAreaStyle: {
        borderColor: '#ddd',
        backgroundColor: '#f8f9fa',
      },
    }
  },
  mounted() {
    this.loadKnowledgeBases()
  },
  methods: {
    // 加载知识库列表
    loadKnowledgeBases() {
      this.$http
        .get('/get-knowledge-bases')
        .then((response) => {
          this.knowledgeBases = response || []
        })
        .catch((error) => {
          console.error('获取知识库列表失败:', error)
          this.knowledgeBases = []
        })
    },

    // 选择知识库
    selectKnowledgeBase(kb) {
      this.currentKbId = kb.id
      this.currentKbName = kb.name
      this.loadKbFiles(kb.id)
    },

    // 加载知识库文件
    loadKbFiles(kbId) {
      this.$http
        .get(`/get-kb-files/${kbId}`)
        .then((response) => {
          this.files = response || []
        })
        .catch((error) => {
          console.error('获取文件列表失败:', error)
          this.files = []
        })
    },

    // 触发文件上传
    triggerFileUpload() {
      this.$refs.fileInput.click()
    },

    // 处理文件上传
    handleFileUpload(event) {
      const files = event.target.files
      if (files.length > 0) {
        this.uploadFiles(files)
      }
      // 重置文件输入框
      event.target.value = ''
    },

    // 上传文件
    uploadFiles(files) {
      this.uploading = true

      const formData = new FormData()
      formData.append('kb_id', this.currentKbId)

      for (let i = 0; i < files.length; i++) {
        formData.append('files', files[i])
      }

      this.$http
        .post('/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        })
        .then((response) => {
          const data = response
          if (data) {
            this.loadKbFiles(this.currentKbId)
            this.$message.success('上传成功')
          } else {
            this.$message.error(
              '上传失败: ' + (data && data.error ? data.error : '未知错误')
            )
          }
        })
        .catch((error) => {
          console.error('上传文件失败:', error)
          this.$message.error('上传文件失败，请重试')
        })
        .finally(() => {
          this.uploading = false
        })
    },

    // 处理文件拖拽悬停
    handleDragOver() {
      this.uploadAreaStyle = {
        borderColor: '#3498db',
        backgroundColor: '#eef7ff',
      }
    },

    // 处理文件拖拽离开
    handleDragLeave() {
      this.uploadAreaStyle = {
        borderColor: '#ddd',
        backgroundColor: '#f8f9fa',
      }
    },

    // 处理文件拖拽释放
    handleDrop(event) {
      this.uploadAreaStyle = {
        borderColor: '#ddd',
        backgroundColor: '#f8f9fa',
      }

      if (this.currentKbId) {
        const files = event.dataTransfer.files
        if (files.length > 0) {
          this.uploadFiles(files)
        }
      } else {
        this.$message.warning('请先选择一个知识库')
      }
    },

    // 删除知识库
    handleDeleteKb(kb) {
      if (kb.is_default) {
        this.$message.warning('默认知识库不能删除')
        return
      }

      this.$confirm(
        `确定要删除知识库 "${kb.name}" 吗？\n此操作不可撤销！`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          this.$http
            .post('/delete-knowledge-base', {
              kbId: kb.id,
            })
            .then((response) => {
              const data = response
              if (data) {
                this.loadKnowledgeBases()

                // 如果删除的是当前选中的知识库，清除当前选择
                if (this.currentKbId === kb.id) {
                  this.currentKbId = null
                  this.currentKbName = ''
                  this.files = []
                }
                this.$message.success('删除知识库成功')
              } else {
                this.$message.error(
                  '删除失败: ' + (data && data.error ? data.error : '未知错误')
                )
              }
            })
            .catch((error) => {
              console.error('删除知识库失败:', error)
              this.$message.error('删除知识库失败，请重试')
            })
        })
        .catch(() => {
          // 用户取消删除
        })
    },

    // 删除文件
    handleDeleteFile(file) {
      this.$confirm(`确定要删除文件 "${file.original_name}" 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$http
            .post('/delete-file', {
              fileId: file.id,
              kbId: this.currentKbId,
            })
            .then((response) => {
              const data = response
              if (data) {
                this.loadKbFiles(this.currentKbId)
                this.$message.success('删除成功')
              } else {
                this.$message.error(
                  '删除失败: ' + (data && data.error ? data.error : '未知错误')
                )
              }
            })
            .catch((error) => {
              console.error('删除文件失败:', error)
              this.$message.error('删除文件失败，请重试')
            })
        })
        .catch(() => {
          // 用户取消删除
        })
    },

    // 格式化日期
    formatDate(dateString) {
      const date = new Date(dateString)
      return `${
        date.getMonth() + 1
      }-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`
    },

    // 返回上一页
    goBack() {
      this.$router.push('/')
    },

    // 打开知识库创建页面
    openKnowledgeBaseModal() {
      this.$router.push('/knowledge-base')
    },
  },
}
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.app-container {
  display: flex;
  height: 100vh;
  width: 100%;
}

.sidebar {
  width: 280px;
  background-color: #fff;
  border-right: 1px solid #e1e8ed;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 15px;
  border-bottom: 1px solid #e1e8ed;
  font-weight: bold;
  font-size: 1.2em;
  color: #2c3e50;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.add-kb-btn {
  padding: 8px 12px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9em;
}

.add-kb-btn:hover {
  background-color: #2980b9;
}

.kb-list {
  flex-grow: 1;
  overflow-y: auto;
  padding: 10px;
}

.kb-item {
  padding: 12px 15px;
  border-radius: 6px;
  cursor: pointer;
  margin-bottom: 8px;
  transition: all 0.3s;
  background-color: #fff;
  border: 1px solid #e1e8ed;
  display: flex;
  align-items: center;
}

.kb-content {
  flex: 1;
  min-width: 0;
}

.kb-name {
  font-weight: 500;
  margin-bottom: 4px;
  word-wrap: break-word;
  word-break: break-all;
}

.kb-item:hover {
  background-color: #f5f7fa;
}

.kb-item.active {
  background-color: #e3f2fd;
  color: #3498db;
  border-color: #3498db;
}

.kb-info {
  font-size: 0.85em;
  color: #666;
}

.main-content {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

.content-header {
  padding: 15px 20px;
  border-bottom: 1px solid #e1e8ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.current-kb-name {
  font-size: 1.1em;
  font-weight: bold;
  color: #2c3e50;
}

.upload-btn {
  padding: 10px 20px;
  background-color: #27ae60;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  font-size: 0.9em;
}

.upload-btn:hover {
  background-color: #219a52;
}

.file-tabs {
  display: flex;
  padding: 10px 20px 0;
}

.file-tab {
  padding: 8px 15px;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  font-size: 0.9em;
}

.file-tab.active {
  border-bottom: 2px solid #3498db;
  color: #3498db;
  font-weight: 500;
}

.file-content {
  flex-grow: 1;
  overflow-y: auto;
  padding: 20px;
}

.upload-area {
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 40px;
  text-align: center;
  background-color: #f8f9fa;
  margin-bottom: 20px;
  transition: all 0.3s;
}

.upload-area:hover {
  border-color: #3498db;
  background-color: #eef7ff;
}

.file-list {
  margin-top: 20px;
}

.file-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  border: 1px solid #e1e8ed;
  border-radius: 6px;
  margin-bottom: 10px;
  background-color: #fff;
}

.file-info {
  display: flex;
  align-items: center;
}

.file-icon {
  margin-right: 12px;
  font-size: 1.5em;
  color: #3498db;
}

.file-details {
  display: flex;
  flex-direction: column;
}

.file-name {
  font-weight: 500;
}

.file-meta {
  font-size: 0.85em;
  color: #666;
}

.file-actions,
.kb-actions {
  display: flex;
  align-items: center;
}

.file-status {
  margin-right: 15px;
  font-size: 0.85em;
  color: #27ae60;
}

.file-action-btn,
.kb-action-btn {
  background: none;
  border: none;
  cursor: pointer;
  color: #666;
  margin-left: 10px;
  padding: 5px;
  display: block;
  font-size: 1.1em;
}

.file-action-btn:hover,
.kb-action-btn:hover {
  color: #e74c3c;
  transform: scale(1.1);
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.empty-state i {
  font-size: 4em;
  margin-bottom: 20px;
}
</style>
